package com.hknc.btscale.service;

import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hknc.btscale.BaseApplication;
import com.hknc.btscale.bean.Constants;
import com.hknc.btscale.bean.WSDataBean;
import com.hknc.btscale.utils.BTSendDataUtils;
import com.hknc.btscale.utils.SPUtils;
import com.hknc.btscale.utils.WSClient;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

import cn.hutool.crypto.digest.otp.TOTP;
import cn.wandersnail.bluetooth.BTManager;

/**
 * 打开websocket的service
 */
public class WebSocketService extends Service {
    private WSClient client;
    private static final String TAG = "WebSocketService";
    private String stallId, marketId;
    private static final long HEART_BEAT_RATE = 3 * 1000;//每隔3秒进行一次对长连接的心跳检测
    private Handler mHandler = new Handler();
    private Runnable heartBeatRunnable = new Runnable() {
        @Override
        public void run() {
            if (client != null) {
                if (client.isClosed()) {
                    reconnectWs();
                }
            } else {
                //如果client已为空，重新初始化websocket
                wsConnect(stallId, marketId);
            }
            //定时对长连接进行心跳检测
            mHandler.postDelayed(this, HEART_BEAT_RATE);
        }
    };
    private boolean isClosed;

    /**
     * 开启重连
     */
    private void reconnectWs() {
        mConnectCallBack.connect(false);
        mHandler.removeCallbacks(heartBeatRunnable);
        if (!isClosed) {
            new Thread() {
                @Override
                public void run() {
                    try {
                        //重连
                        client.reconnectBlocking();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            stallId = intent.getStringExtra("stallId");
            marketId = intent.getStringExtra("marketId");
            wsConnect(stallId, marketId);
//            mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        client = new WSClient(URI.create(Constants.WS_URL)) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                super.onOpen(handshakedata);

                if (client != null && client.isOpen()) {
                    Log.e(TAG, "onOpen: =============>");
                    sendHandler.removeCallbacks(mRunnable);
                    sendHandler.postDelayed(mRunnable, 5000);
                }
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                super.onClose(code, reason, remote);
                Log.e(TAG, "onClose: =============>"+code+"=="+reason+"=="+remote);
                if (code==-1)
                {
                    sendHandler.removeCallbacks(mRunnable);
                    sendHandler.postDelayed(mRunnable, 5000);
                }
            }

            @Override
            public void onError(Exception ex) {
                super.onError(ex);
                Log.e(TAG, "onError: =============>"+ex.getMessage());
            }

            @Override
            public void onMessage(String message) {
                super.onMessage(message);
                //打开广播，监听ws获得到的数据
                Intent intentBroadcast = new Intent();
                intentBroadcast.setAction("com.xch.servicecallback.content");
                intentBroadcast.putExtra("message", message);
                if (BaseApplication.sDevice!=null){
                    intentBroadcast.putExtra("device", BaseApplication.sDevice);
                }
                sendBroadcast(intentBroadcast);
                Log.e(TAG, "onMessage: " + message);
                mConnectCallBack.connect(true);
            }
        };
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * websocket连接初始化
     *
     * @param stallId
     * @param marketId
     */
    private void wsConnect(String stallId, String marketId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String desStr = "{\"stallId\": " +
                        stallId +
                        ", \"type\": \"1\",\"marketId\":" +
                        marketId +
                        "}";

                try {
                    if (client.isOpen()) {
                        return;
                    }
                    client.connectBlocking();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private Gson gson = new Gson();
    private WSDataBean wsDataBean = new WSDataBean();

    private Handler sendHandler = new Handler();
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            wsDataBean.setMarketId(marketId);
            wsDataBean.setType("1");
            wsDataBean.setStallId(stallId);
            String data = gson.toJson(wsDataBean);
            Log.e(TAG, "run: " + data);
            if (client != null) {
                if (client.isClosed()) {
                    reconnectWs();
                }
            } else {
                //如果client已为空，重新初始化websocket
                wsConnect(stallId, marketId);
            }
            //定时对长连接进行心跳检测
            sendHandler.postDelayed(mRunnable, 60 * 1000);

            if (client != null && client.isOpen()) {
                client.send(data);
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        isClosed = true;
        Log.e(TAG, "onDestroy: " + "WebSocket");
        try {
            sendHandler.removeCallbacks(mRunnable);
            client.closeBlocking();
            stopSelf();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static ConnectCallBack mConnectCallBack;

    public static ConnectCallBack getConnectCallBack() {
        return mConnectCallBack;
    }

    public static void setConnectCallBack(ConnectCallBack connectCallBack) {
        mConnectCallBack = connectCallBack;
    }

    public interface ConnectCallBack {
        void connect(boolean isConnect);
    }
}